﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Shared.Method;
using Shared.Model;
using Client;
using StationTestDll;
using System.Threading.Tasks;
using Shared.DJDBDK;

namespace ModemWrite
{
    public partial class FormTestThree : UserControl
    {
        private string _stationIp = null;

        private string _localIp = null;
        private int _localPort = 0;

        private string _modemIp = null;
        private string _modemUser = null;
        private string _modemPwd = null;

        private int _myFormNum = 0;

        private long _nodeId = 0;
        //private YcdTelnetClass _telnet = null;
        //private string _ifReset = "0";

        //增加一个事件传递正在写入信息的指令
        public event Action<int> OnTesting;

        public event Action<bool> OnVoiceResult;

        private string _log = "";

        //所有的产品类型信息
        private List<Device_Type> _listType = null;

        //private int _testNum = 0;

        //获取初始化数据
        public FormTestThree(string localIp, int localPort,
            string modemIp, string modemUser, string modemPwd,
            int formNum, List<Device_Type> listType, string stationIp = "127.0.0.1")
        {
            _stationIp = stationIp;

            _localIp = localIp;
            _localPort = localPort;

            _modemIp = modemIp;
            _modemUser = modemUser;
            _modemPwd = modemPwd;

            _myFormNum = formNum;

            _listType = listType;

            //_ifReset = ifReset;

            if (string.IsNullOrEmpty(localIp)
                || string.IsNullOrEmpty(modemIp)
                || string.IsNullOrEmpty(modemUser)
                || string.IsNullOrEmpty(modemPwd)
                || localPort <= 1024)
            {
                //初始化的参数不正确
                MessageBox.Show(string.Format("窗口：{0}，初始化参数不正确", _myFormNum));
                this.Dispose();//销毁窗口
            }

            //从APPCONFIG获取配置
            string nodeId = AppSetting.GetSetValue("StationNodeId");
            if (string.IsNullOrEmpty(nodeId) == false) long.TryParse(nodeId, out _nodeId);

            InitializeComponent();
        }

        //输入MAC
        private void textBoxMacAddr_KeyPress(object sender, KeyPressEventArgs e)
        {
            //只能输入16进制数字和回车符号'\r'或者'\n'，MAC地址中的字符只能位0-9,A~F
            if (e.KeyChar == '\n' || e.KeyChar == '\r')
            {
                e.Handled = true;
                if (this.textBoxMacAddr.Text.Trim().Length != 12)
                {
                    AppendRichTextBox("MAC地址不为12位数");
                    this.textBoxMacAddr.Clear();
                    this.textBoxMacAddr.Focus();
                }
                else
                {
                    //判断MAC是否已经绑定过SN号码，如果已经绑定了，则直接开始写入信息
                    Action d = new Action(TestThree);
                    d.BeginInvoke(null, null);
                }
            }
            else if ((e.KeyChar >= 'a' && e.KeyChar <= 'f')
                || (e.KeyChar >= 'A' && e.KeyChar <= 'F')
                || (e.KeyChar >= '0' && e.KeyChar <= '9')
                || (e.KeyChar == 8))
            {
                //判断是否位16进制字符，将小写全部转为大写
                e.Handled = false;
            }
            else
            {
                MessageBox.Show("只能输入数字和A-F");
                e.Handled = true;
            }
        }

        private void TestThree()
        {
            SetMacTextBoxEnable(false);

            string mac = this.textBoxMacAddr.Text.Trim();

            //判断此MAC地址是否已经存在了
            if (PublicData.ListAddress.ContainsKey(mac))
            {
                AppendRichTextBox("此MAC地址正在其他窗口使用，请勿重复扫描");
                FinallyDone(mac);
                return;
            }
            else
            {
                PublicData.ListAddress.Add(mac, mac);
            }

            //到数据库中查找是否存在相应的MAC
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.MACAddr = mac;

            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);
            if (selectDevice.result == false)
            {
                AppendRichTextBox("未能在数据库中找到MAC地址对应的数据，检查失败");
                //SetTestResult(false);

                //删除相关的MAC信息
                FinallyDone(mac);
                return;
            }

            //判断是否需要进行此工序
            bool hasChecked = ProductCheck(mac);

            if (hasChecked)
            {
                AppendRichTextBox("此产品已经通过了信息检查，无需再次检查");
                //SetTestResult(true);

                //删除相关的MAC信息
                FinallyDone(mac,true);
                return;
            }

            _log = "";

            OnTesting?.Invoke(_myFormNum);//发送正在写入信息的指令

            //WriteLog("判断是否可以进行信息检查的工作");
            AppendRichTextBox("判断是否可以进行信息检查的工作");

            string msg = "";

            //判断是否可以开始信息检查的工作
            bool canTest = StationTest.IfCanTest(mac, ref msg, _stationIp);

            //WriteLog(msg);
            AppendRichTextBox(msg);

            if (canTest == false)
            {
                //删除相关的MAC信息
                FinallyDone(mac);
                return ;
            }

            //信息检查
            var checkMsg = ModemTestAndCheck(selectDevice.value[0]);

            //写LOG信息
            bool writeLogResult = StationTest.SaveTestData(mac, checkMsg, _log, ref msg, _localIp);
            AppendRichTextBox(string.Format("写LOG信息结果为：{0}，返回信息为：{1}", writeLogResult, msg));

            AppendRichTextBox("融合测试工作完成");

            FinallyDone(mac, checkMsg);
        }

        private bool ProductCheck(string mac)
        {
            //查找过程表，看有没有一条已经通过的数据
            PRODUCT productW = new PRODUCT();
            productW.SetWhere();

            productW.MAC = mac;
            productW.TEST_RESULT = "Y";
            productW.NODE_ID = _nodeId;
            productW.NODE_STATE = true;//表示工序完成

            var selectProduct = MethodWcf.SelectProductCountClient(productW);

            if (selectProduct.result && selectProduct.message == "1") return true;
            return false;
        }

        private bool ModemTestAndCheck(Device_Data deviceData)
        {

            //显示正在测试当中
            SetTestResult(true, "WAITFOR");

            //获取产品型号的相关数据
            var deviceType = GetDeviceType(deviceData.DeviceType,deviceData.HW_PROVINCE_NAME);

            if (deviceType == null)
            {
                //WriteLog("未能获取产品的类型信息");
                AppendRichTextBox("未能获取产品的类型信息");

                //FinallyDone(deviceData.MACAddr);
                return false;
            }

            //PING测试
            int pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _modemIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }

                System.Threading.Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                AppendRichTextBox("未能成功PING通光猫");
                return false;
            }

            //尝试5次1秒一次
            SetTestResult(false, "TESTING");

            ////初始化telnet
            YcdTelnetClass tel = null;
            for (int i = 0; i < 3; i++)
            {

                ////初始化telnet
                tel = TelnetModem();

                if (tel == null)
                {
                    AppendRichTextBox("TELNET光猫失败");
                }
                else
                {
                    break;
                }

                System.Threading.Thread.Sleep(5000);
            }

            if (tel == null)
            {
                return false;
            }

            bool checkResult = false;

            if (deviceData.DeviceType == "PT924 G")
            {
                //MTK方案的GPON
                checkResult = CheckDeviceDataMtk(deviceData, deviceType, tel);
            }
            else
            {
                //R方案的EPON和GPON
                checkResult = CheckDeviceDataR(deviceData, deviceType, tel);
            }

            if (checkResult == false)
            {
                tel.Send("exit");
                tel.Close();
                return false;
            }

            //语音测试
            string keyWord = GetKeyWord(deviceData);
            bool voiceTestResult = VoiceButtonTest(tel, deviceData.MACAddr, deviceData);

            if (voiceTestResult == false)
            {
                //关闭socket
                tel.Send("exit");
                tel.Close();

                return false;
            }

            if (checkResult&&voiceTestResult)//当写信息的结果为true/写入结果为true/保存log为true时，才能够算是成功的测试了
            {
                //恢复出厂设置
                ResetModem(TelnetModem(), deviceType.DeviceType);
            }

            //关闭socket
            tel.Send("exit");
            tel.Close();

            //等待PING通光猫

            AppendRichTextBox("等待光猫重启完成，等待连接……");
            SetTestResult(true, "WAITFOR");
            //连续PING通4次才算连接上了

            pingOkTimes = 0;
            for (int i = 0; i < 80; i++)
            {
                if (PingBaseClass.PingTest(_localIp, _modemIp))
                {
                    pingOkTimes++;
                    if (pingOkTimes >= 4)
                        break;
                }
                else
                {
                    pingOkTimes = 0;
                }

                System.Threading.Thread.Sleep(500);
            }

            if (pingOkTimes < 4)
            {
                AppendRichTextBox("未能成功PING通光猫");
                return false; 
            }

            //出厂检查部分
            var factoryCheckResult = FactotyCheck(deviceData.MACAddr, deviceData, deviceType);

            return checkResult&&voiceTestResult&&factoryCheckResult;
        }

        #region 信息检查

        /// <summary>
        /// 写R方案的信息
        /// </summary>
        /// <param name="deviceData"></param>
        /// <returns></returns>
        private bool CheckDeviceDataR(Device_Data deviceData, Device_Type deviceType, YcdTelnetClass tel)
        {
            //检查key copyright province信息是否是空值
            if (string.IsNullOrEmpty(deviceData.HW_CIPHER) || string.IsNullOrEmpty(deviceData.HW_PROVINCE_NAME) || string.IsNullOrEmpty(deviceType.HWCopyright))
            {
                SetResultOne("KEY COPYRIGHT PROVINCE三个数据为空", false);
                return false;
            }

            ////清除产测区
            //var writeResult = WriteAndReadMsg(tel, "default_hsnw", null, "Fetch", null);
            //if (writeResult == false) { SetResultOne("清除产测区失败", false); return false; }
            //else { SetResultOne("清除产测区成功", true); }

            //MAC烧录
            var writeResult = WriteAndReadMsg(tel, string.Format("flash set ELAN_MAC_ADDR {0}", deviceData.MACAddr), "flash get ELAN_MAC_ADDR", deviceData.MACAddr, deviceData.MACAddr);
            if (writeResult == false) { SetResultOne("检查MAC地址失败", false); return false; }
            else { SetResultOne("检查MAC地址成功", true); }

            //设备序列号
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_SERIAL_NO {0}", deviceData.OUI2), "flash get HW_SERIAL_NO", deviceData.OUI2, deviceData.OUI2);
            if (writeResult == false) { SetResultOne("检查设备序列号失败", false); return false; }
            else { SetResultOne("检查设备序列号成功", true); }

            //设备型号
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_PRODUCTCLASS {0}", deviceData.DeviceType.Replace(" ", "")), "flash get HW_CWMP_PRODUCTCLASS", deviceData.DeviceType.Replace(" ", ""), deviceData.DeviceType.Replace(" ", ""));
            if (writeResult == false) { SetResultOne("检查设备型号失败", false); return false; }
            else { SetResultOne("检查设备型号成功", true); }

            //校验软件版本信息
            writeResult = WriteAndReadMsg(tel, null, "cat /etc/swver", null, deviceType.SWVersion);
            if (writeResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            else { SetResultOne("检查软件版本成功", true); }

            //校验软件编译时间
            writeResult = WriteAndReadMsg(tel, null, "cat /etc/swver", null, deviceType.BuildTime);
            if (writeResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }

            //硬件版本
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_HWVER {0}", deviceType.HWVersion), "flash get HW_HWVER", deviceType.HWVersion, deviceType.HWVersion);
            if (writeResult == false) { SetResultOne("检查设备硬件版本失败", false); return false; }
            else { SetResultOne("检查设备硬件版本成功", true); }

            //普通用户密码
            writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_USER_PASSWORD {0}", deviceData.WedPassword), "flash get DEFAULT_USER_PASSWORD", deviceData.WedPassword, deviceData.WedPassword);
            if (writeResult == false) { SetResultOne("检查普通用户密码失败", false); return false; }
            else { SetResultOne("检查普通用户密码成功", true); }

            //无线名称
            writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_SSID {0}", deviceData.WIFI_SSID), "flash get DEFAULT_WLAN_SSID", deviceData.WIFI_SSID, deviceData.WIFI_SSID);
            if (writeResult == false) { SetResultOne("检查WIFI名称失败", false); return false; }
            else { SetResultOne("检查WIFI名称成功", true); }

            //无线密钥
            writeResult = WriteAndReadMsg(tel, string.Format("flash set DEFAULT_WLAN_WPAKEY {0}", deviceData.WIFI_Password), "flash get DEFAULT_WLAN_WPAKEY", deviceData.WIFI_Password, deviceData.WIFI_Password);
            if (writeResult == false) { SetResultOne("检查WIFI密码失败", false); return false; }
            else { SetResultOne("检查WIFI密码成功", true); }

            //ITV名称
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_SSID2ND {0}", deviceData.ITV_SSID), "flash get HW_SSID2ND", deviceData.ITV_SSID, deviceData.ITV_SSID);
            if (writeResult == false) { SetResultOne("检查ITV SSID名称失败", false); return false; }
            else { SetResultOne("检查ITV SSID成功", true); }

            //ITV密钥
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_WPAKEY2ND {0}", deviceData.ITV_Password), "flash get HW_WPAKEY2ND", deviceData.ITV_Password, deviceData.ITV_Password);
            if (writeResult == false) { SetResultOne("检查ITV 密码失败", false); return false; }
            else { SetResultOne("检查ITV 密码成功", true); }

            //光模块型号
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_MODEL {0}", deviceData.ProductCode), "flash get HW_LIGHT_MODEL", deviceData.ProductCode, deviceData.ProductCode);
            if (writeResult == false) { SetResultOne("检查光模块型号失败", false); return false; }
            else { SetResultOne("检查光模块型号成功", true); }

            //光模块序列号
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_LIGHT_SN {0}", deviceData.LightModuleSN), "flash get HW_LIGHT_SN", deviceData.LightModuleSN, deviceData.LightModuleSN);
            if (writeResult == false) { SetResultOne("检查光模块序列号失败", false); return false; }
            else { SetResultOne("检查光模块序列号成功", true); }

            //GPON_SN，只有GPON才检查SN号码
            if (deviceType.XPONMode == "GPON")
            {
                writeResult = WriteAndReadMsg(tel, "flash get GPON_SN", string.Format("flash set GPON_SN {0}", deviceData.XPON_SN), deviceData.XPON_SN, "=" + deviceData.XPON_SN);
                if (writeResult == false) { SetResultOne("检查GPON_SN失败", false); return false; }
                else { SetResultOne("检查GPON_SN成功", true); }
            }

            //XPON型号
            string ponMode = null;
            if (deviceType.XPONMode == "GPON")
            {
                ponMode = "1";
            }
            else
            {
                ponMode = "2";
            }

            writeResult = WriteAndReadMsg(tel, string.Format("flash set PON_MODE {0}", ponMode), "flash get PON_MODE", ponMode, ponMode);
            if (writeResult == false) { SetResultOne("检查PON的型号失败", false); return false; }
            else { SetResultOne("检查PON的型号成功", true); }

            //厂商名称
            string companyName = "youhua";
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CWMP_MANUFACTURER {0}", companyName), "flash get HW_CWMP_MANUFACTURER", companyName, companyName);
            if (writeResult == false) { SetResultOne("检查厂商名称失败", false); return false; }
            else { SetResultOne("检查厂商名称成功", true); }

            //版本校验码key
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_CIPHER {0}", deviceData.HW_CIPHER), "flash get HW_CIPHER", deviceData.HW_CIPHER, deviceData.HW_CIPHER);
            if (writeResult == false) { SetResultOne("检查版本校验码KEY失败", false); return false; }
            else { SetResultOne("检查版本校验码KEY成功", true); }

            //软件版本校验码copyright
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_COPYRIGHT {0}", deviceType.HWCopyright), "flash get HW_COPYRIGHT", deviceType.HWCopyright, deviceType.HWCopyright);
            if (writeResult == false) { SetResultOne("检查软件版本校验码copyright失败", false); return false; }
            else { SetResultOne("检查软件版本校验码copyright成功", true); }

            //检查省份信息
            writeResult = WriteAndReadMsg(tel, string.Format("flash set HW_PROVINCE_NAME {0}", deviceData.HW_PROVINCE_NAME), "flash get HW_PROVINCE_NAME", deviceData.HW_PROVINCE_NAME, deviceData.HW_PROVINCE_NAME);
            if (writeResult == false) { SetResultOne("检查省份信息失败", false); return false; }
            else { SetResultOne("检查省份信息成功", true); }

            //检查长发光是否关闭了
            //关闭常发光指令
            writeResult = WriteAndReadMsg(tel, null, "flash get USER_FACTORY_BEFORE_RUN", null, "USER_FACTORY_BEFORE_RUN=0");
            if (writeResult == false) { SetResultOne("检查长发光，未关闭", false); return false; }
            else { SetResultOne("检查长发光，已关闭", true); }

            return true;
        }
        /// <summary>
        /// 检查MTK方案的信息
        /// </summary>
        /// <param name="deviceData"></param>
        /// <returns></returns>
        private bool CheckDeviceDataMtk(Device_Data deviceData, Device_Type deviceType, YcdTelnetClass tel)
        {
            ////清除区域指令
            //var writeResult = WriteAndReadMsg(tel, "prolinecmd clear 1", null, "write", null);
            //if (writeResult == false) { SetResultOne("清除区域指令失败", false); return false; }
            //else { SetResultOne("清除区域指令成功", true); }


            //检查MAC
            var writeResult = WriteAndReadMsg(tel, string.Format("sys mac {0} -n", deviceData.MACAddr), null, "addr", null);
            if (writeResult == false) { SetResultOne("检查MAC地址失败", false); return false; }
            else { SetResultOne("检查MAC地址成功", true); }

            //检查productclass
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd productclass set {0}", deviceData.DeviceType.Replace(" ", ""))
                , "prolinecmd productclass display"
                , "readflash"
                , deviceData.DeviceType.Replace(" ", ""));

            if (writeResult == false) { SetResultOne("检查Productclass失败", false); return false; }
            else
            {
                SetResultOne("检查Productclass成功", true);
            }
            //检查oui1
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd manufacturerOUI set  {0}", deviceData.OUI1)
                , "prolinecmd manufacturerOUI display"
                , "readflash"
                , deviceData.OUI1);

            if (writeResult == false) { SetResultOne("检查OUI1失败", false); return false; }
            else { SetResultOne("检查OUI1成功", true); }
            //检查oui2
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd serialnum set  {0}", deviceData.OUI2)
                , "prolinecmd serialnum display"
                , "readflash"
                , deviceData.OUI2);

            if (writeResult == false) { SetResultOne("检查OUI2失败", false); return false; }
            else { SetResultOne("检查OUI2成功", true); }
            //检查硬件版本信息
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd hwver set  {0}", deviceType.HWVersion)
                , "prolinecmd hwver display"
                , "readflash"
                , deviceType.HWVersion);

            if (writeResult == false) { SetResultOne("检查硬件版本失败", false); return false; }
            else { SetResultOne("检查硬件版本成功", true); }
            //校验软件版本信息
            writeResult = WriteAndReadMsg(tel
                , null
                , "cat /etc/swver"
                , null
                , deviceType.SWVersion);

            if (writeResult == false) { SetResultOne("检查软件版本失败", false); return false; }
            else { SetResultOne("检查软件版本成功", true); }
            //校验软件编译时间
            writeResult = WriteAndReadMsg(tel
                , null
                , "cat /etc/swver"
                , null
                , deviceType.BuildTime);

            if (writeResult == false) { SetResultOne("校验编译时间失败", false); return false; }
            else { SetResultOne("校验编译时间成功", true); }
            //检查光模块SN
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd lightmodulesn set {0}", deviceData.LightModuleSN)
                , "prolinecmd lightmodulesn display"
                , "readflash"
                , deviceData.LightModuleSN);

            if (writeResult == false) { SetResultOne("检查光模块SN失败", false); return false; }
            else { SetResultOne("检查光模块SN成功", true); }
            //检查光模块型号
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd lightmodule set {0}", deviceData.ProductCode)
                , "prolinecmd lightmodule display"
                , "readflash"
                , deviceData.ProductCode);

            if (writeResult == false) { SetResultOne("检查光模块型号失败", false); return false; }
            else { SetResultOne("检查光模块型号成功", true); }
            //检查WIFI SSID
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd ssid  set {0}", deviceData.WIFI_SSID)
                , "prolinecmd ssid  display"
                , "readflash"
                , deviceData.WIFI_SSID);

            if (writeResult == false) { SetResultOne("检查wifi ssid失败", false); return false; }
            else { SetResultOne("检查WiFi ssid成功", true); }
            //检查WIFI密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd wpakey  set {0}", deviceData.WIFI_Password)
                , "prolinecmd wpakey  display"
                , "readflash"
                , deviceData.WIFI_Password);

            if (writeResult == false) { SetResultOne("检查WiFi密码失败", false); return false; }
            else { SetResultOne("检查wifi密码成功", true); }
            //检查ITVSSID
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd ssid2nd  set {0}", deviceData.ITV_SSID)
                , "prolinecmd ssid2nd   display"
                , "readflash"
                , deviceData.ITV_SSID);

            if (writeResult == false) { SetResultOne("检查ITV SSID失败", false); return false; }
            else { SetResultOne("检查ITV SSID 成功", true); }
            //检查ITV密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd wpakey2nd  set {0}", deviceData.ITV_Password)
                , "prolinecmd wpakey2nd   display"
                , "readflash"
                , deviceData.ITV_Password);

            if (writeResult == false) { SetResultOne("检查ITV 密码失败", false); return false; }
            else { SetResultOne("检查ITV密码成功", true); }
            //检查web用户名
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd webAccount  set {0}", deviceData.WedUser)
                , "prolinecmd webAccount   display"
                , "readflash"
                , deviceData.WedUser);

            if (writeResult == false) { SetResultOne("检查web用户名称失败", false); return false; }
            else { SetResultOne("检查web用户名称成功", true); }
            //检查web密码
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd webpwd set {0}", deviceData.WedPassword)
                , "prolinecmd webpwd  display"
                , "readflash"
                , deviceData.WedPassword);

            if (writeResult == false) { SetResultOne("检查web密码失败", false); return false; }
            else { SetResultOne("检查web密码成功", true); }
            //检查XPON modem
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd xponmode set {0}", deviceType.XPONMode)
                , "prolinecmd xponmode display"
                , "readflash"
                , deviceType.XPONMode);

            if (writeResult == false) { SetResultOne("检查XPON MODEM失败", false); return false; }
            else { SetResultOne("检查XPON MODEM成功", true); }
            //检查XPON SN
            writeResult = WriteAndReadMsg(tel
                , string.Format("prolinecmd xponsn set {0}", deviceData.XPON_SN)
                , "prolinecmd xponsn display"
                , "readflash"
                , deviceData.XPON_SN);

            if (writeResult == false) { SetResultOne("检查XPON_SN失败", false); return false; }
            else { SetResultOne("检查XPON_SN成功", true); }

            //检查长发光
            return true;
        }

        //检查信息和回显信息，MTK和R通用
        private bool WriteAndReadMsg(YcdTelnetClass tel, string writeCmd, string readCmd, string keyWordWrite, string keyWordRead)
        {
            if (string.IsNullOrEmpty(writeCmd) && string.IsNullOrEmpty(readCmd)) return false;

            //修改writeCmd为空，不写信息
            writeCmd = null;

            //写信息
            if (string.IsNullOrEmpty(writeCmd) == false)
            {
                tel.Send(writeCmd);

                string value;
                bool hasKey = tel.GetReturnMsg(keyWordWrite.Trim(),out value);

                //写LOG
                //WriteLog(value);
                AppendRichTextBox(value);

                if (hasKey==false) return false;
            }

            //读取信息
            if (string.IsNullOrEmpty(readCmd) == false)
            {
                tel.Send(readCmd);

                string value;
                 bool hasKey= tel.GetReturnMsg(keyWordRead.Trim(),out value);


                //写log
                //WriteLog(value);
                AppendRichTextBox(value);

                if (hasKey==false) return false;
            }

            return true;
        }
        #endregion

        private int portOffset = DateTime.Now.Second;

        /// <summary>
        /// 连接并登陆光猫，返回类，若为空则链接失败
        /// </summary>
        /// <returns></returns>
        private YcdTelnetClass TelnetModem()
        {
            //使用新的类YcdTelnetClass
            if (portOffset >= 500) portOffset = 0;
            portOffset++;

            YcdTelnetClass telnet = new YcdTelnetClass(_modemIp, _localIp, _localPort + portOffset);
            if (telnet.Connect() == false)
            {
                return null;
            }

            System.Threading.Thread.Sleep(500);

            string value;
            if (telnet.GetReturnMsg("login",out value))
            {
                AppendRichTextBox("输入用户名称……");
                telnet.Send(_modemUser);
            }
            else
            {
                telnet.Send("exit");
                telnet.Close();
                return null;
            }

            if (telnet.GetReturnMsg("Password:",out value) )
            {
                AppendRichTextBox("输入用户密码中……");
                telnet.Send(_modemPwd);
            }
            else
            {
                telnet.Send("exit");
                telnet.Close();
                return null;
            }

            bool hasKey = telnet.GetReturnMsg("#",out value);

            if (hasKey==false) return null;

            AppendRichTextBox(value);

            return telnet;
        }
        /// <summary>
        /// 重置光猫
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="deviceType"></param>
        private void ResetModem(YcdTelnetClass tel, string deviceType)
        {
            if (deviceType == "PT924 G")
            {
                //重置光猫
                tel.Send("mtd erasesector 0 romfile");

                string msg;
                 bool hasKey= tel.GetReturnMsg("#",out msg);

                //WriteLog(msg);

                AppendRichTextBox(msg);
                tel.Send("mtd erasesector 0 reservearea");
                hasKey = tel.GetReturnMsg("#",out msg);

                AppendRichTextBox(msg);
                //WriteLog(msg);

                tel.Send("prolinecmd restore default");

                AppendRichTextBox("重置光猫开始……");
            }
            else if (deviceType == "PT924" || deviceType == "PT924G")
            {
                //重置光猫
                tel.Send("flash default cs");

                string msg;
                 bool hasKey= tel.GetReturnMsg("#",out msg);

                AppendRichTextBox(msg);
                //WriteLog(msg);

                tel.Send("reboot -f");

                AppendRichTextBox("重置光猫开始……");
            }
        }

        #region 语音按键测试

        private bool VoiceButtonTest(YcdTelnetClass tel,string mac,Device_Data device)
        {
            //连接光猫
            ////初始化telnet
            //YcdTelnetClass tel = null;
            //for (int i = 0; i < 3; i++)
            //{
            //    tel = TelnetModem();

            //    if (tel == null)
            //    {
            //        AppendRichTextBox("TELNET光猫失败");
            //    }
            //    else
            //    {
            //        break;
            //    }

            //    System.Threading.Thread.Sleep(2000);
            //}

            if (tel == null)
            {
                return false;
            }

            //获取MAC地址
            //string mac = MacClass.GetModemMacAddress(tel);


            if (mac == null)
            {
                AppendRichTextBox("未能获取MAC地址");
                tel.Send("exit");
                tel.Close();
                return false;
            }

            string msg = "";

            //判断能否进行测试
            //bool canTest = StationTest.IfCanTest(mac, ref msg, _stationIp);
            //AppendRichTextBox(msg);

            //if (canTest == false) return false;

            //设置临时的MAC地址
            //判断是否需要执行此操作

            //获取对应的DEVICE_DATA，并判断是否需要执行操作
            //var device = GetDeviceData(mac);

            //if (device != null && device.PONType == "EPON")
            //{
            //    bool retTemp = SetTempMac(tel);
            //    if (retTemp == false)
            //    {
            //        tel.Send("exit");
            //        tel.Close();

            //        AppendRichTextBox("设置临时MAC失败");
            //        return false;
            //    }
            //    else { SetTestResult(true, "设置临时MAC成功"); }
            //}

            //设置WIFI信道
            //bool setWifi = SetWifiChannel(tel);
            //if (setWifi == false)
            //{
            //    tel.Send("exit");
            //    tel.Close();

            //    AppendRichTextBox("设置WIFI信道失败");

            //    return false;
            //}
            //else { SetTestResult(true, "设置WIFI信道成功"); }

            //开启灯光
            bool ret = TelnetSendAndRecv(tel, "mpctl led on", "bin");

            //System.Threading.Thread.Sleep(5000);

            //执行开始按键测试的命令
            ret = TelnetSendAndRecv(tel, "cat /proc/kmsg & led test start", "#");

            if (ret == false)
            {
                AppendRichTextBox("未能开启按键测试功能");
                StationTest.SaveTestData(mac, false, _log, ref msg, _stationIp);
                AppendRichTextBox(msg);
                return false;
            }

            bool buttonTestResult = ButtonTest(tel);

            //执行结束按键测试的命令_delete_18.2.8_修复四川版本漏洞
            //ret = TelnetSendAndRecv(tel, "led test stop", "/bin/sh:");


            //if (ret == false)
            //{
            //    AppendRichTextBox("未能成功结束按键测试功能");
            //    StationTest.SaveTestData(mac, false, _log, ref msg, _stationIp);
            //    AppendRichTextBox(msg);
            //    return false;
            //}

            if (buttonTestResult == false)
            {
                AppendRichTextBox("按键测试失败");
                tel.Send("exit");
                tel.Close();

                StationTest.SaveTestData(mac, false, _log, ref msg, _stationIp);
                AppendRichTextBox(msg);
                return false;
            }
            else
            {
                //展示测试成功的内容
                SetTestResult(true, "按键测试成功");
            }

            //还原灯光
            //ret = TelnetSendAndRecv(tel, "mpctl led restore", "bin");

            //USB测试
            bool usbTestResult = UsbTest(tel);
            if (usbTestResult == false)
            {
                AppendRichTextBox("USB测试失败");
                tel.Send("exit");
                tel.Close();

                StationTest.SaveTestData(mac, false, _log, ref msg, _stationIp);
                AppendRichTextBox(msg);
                return false;
            }
            else
            {
                //展示测试成功的内容
                SetTestResult(true, "USB测试成功");
            }
            string keyWord = GetKeyWord(device);

            //语言测试
            bool voiceTestResult = VoiceTest(_myFormNum-1, tel, keyWord);

            OnVoiceResult?.Invoke(voiceTestResult);

            if (voiceTestResult == false)
            {
                AppendRichTextBox("语音测试失败");
                tel.Send("exit");
                tel.Close();

                return false;
            }
            else
            {
                //展示测试成功的内容
                SetTestResult(true, "语音测试成功");
            }

            return true;
        }

        private string GetKeyWord(Device_Data device)
        {
            var type = (from t in _listType
                        where t.DeviceType == device.DeviceType && t.PROVINCE == device.HW_PROVINCE_NAME
                        select t).FirstOrDefault();
            if (type == null) return "es";

            if (type.SWVersion == "920" || type.SWVersion == "1052")
            {
                return "es";
            }
            else
            {
                return "VpInitLine";
            }
        }

        private Device_Data GetDeviceData(string mac)
        {
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere();
            deviceW.MACAddr = mac;

            var selectDeviceData = MethodWcf.SelectDeviceDataClient(deviceW);
            if (selectDeviceData.result)
            {
                return selectDeviceData.value[0];
            }

            return null;
        }

        //USB测试
        private bool UsbTest(YcdTelnetClass tel)
        {
            //判断tel是否连接着
            if (tel == null || tel.IsConnected() == false)
            {
                AppendRichTextBox("USB测试失败，传入参数错误");
                return false;
            }

            bool ret = false;

            System.Threading.Thread.Sleep(500);

            //重试10次
            for (int i = 0; i < 10; i++)
            {
                ret = TelnetSendAndRecv(tel, "usbmp", "cat");

                if (ret) break;

                System.Threading.Thread.Sleep(500);
            }

            if (ret) AppendRichTextBox("USB测试成功");
            else
            {
                AppendRichTextBox("USB测试失败");
                return false;
            }

            return true;
        }
        //按键测试
        private bool ButtonTest(YcdTelnetClass tel)
        {
            //判断tel是否连接着
            if (tel == null || tel.IsConnected() == false)
            {
                AppendRichTextBox("按键测试失败，传入参数错误");
                return false;
            }

            bool ret = false;

            //WIFI按钮
            SetTestResult(true, "灯亮，按WIFI按钮");

            System.Threading.Thread.Sleep(1000);

            //重试10次
            for (int i = 0; i < 10; i++)
            {
                string msg;
                ret = tel.GetReturnMsg("wifi", out msg);
                AppendRichTextBox(msg);

                if (ret) break;

                System.Threading.Thread.Sleep(500);
            }

            if (ret) AppendRichTextBox("WIFI按钮测试成功");
            else
            {
                AppendRichTextBox("WIFI按钮测试失败");
                return false;
            }

            //复位按钮
            SetTestResult(true, "按复位按钮");
            //重试10次
            for (int i = 0; i < 10; i++)
            {
                string msg;
                ret = tel.GetReturnMsg("Push Button do nothing", out msg);
                AppendRichTextBox(msg);

                if (ret) break;

                System.Threading.Thread.Sleep(500);
            }

            if (ret) AppendRichTextBox("复位按钮测试成功");
            else
            {
                AppendRichTextBox("复位按钮测试失败");
                return false;
            }

            return true;
        }

        //语音测试，返回true or false
        private bool VoiceTest(int voiceNum, YcdTelnetClass tel, string keyWord = "MPtest")
        {
            //判断参数是否正确
            if (voiceNum > 7 || voiceNum < 0 || tel == null || tel.IsConnected() == false)
            {
                AppendRichTextBox("语音测试失败，传入参数错误");
                return false;
            }

            bool ret = TelnetSendAndRecv(tel, "voipmp", keyWord);//18.1.25修改，兼容R方案1.23日版本

            if (ret == false)
            {
                AppendRichTextBox("未能开启语音测试功能");
                return false;
            }
            else
                AppendRichTextBox("开启语音测试");


            //System.Threading.Thread.Sleep(30000);


            string msg;
            //开始测试语音
            ret = VoiceBaseClass.DialNum(voiceNum, "*159#", out msg);


            AppendRichTextBox(msg);

            tel.GetReturnMsg("#", out msg);

            AppendRichTextBox(msg);

            return ret;
        }
        /// <summary>
        /// TELNET命令
        /// </summary>
        /// <param name="tel"></param>
        /// <param name="cmdStr"></param>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        private bool TelnetSendAndRecv(YcdTelnetClass tel, string cmdStr, string keyWord)
        {
            if (tel == null || tel.IsConnected() == false || string.IsNullOrEmpty(cmdStr) || string.IsNullOrEmpty(keyWord)) return false;

            //发送telnet指令_语音测试
            tel.Send(cmdStr);

            string msg;

            bool ret = tel.GetReturnMsg(keyWord, out msg);

            AppendRichTextBox(msg);

            return ret;
        }
        #endregion

        #region 出厂测试

        private bool FactotyCheck(string mac,Device_Data device,Device_Type deviceType)
        {
            //显示正在测试当中
            SetTestResult(false, "TESTING");

            //等待110秒时间
            for (int i = 4; i > 0; i--)
            {
                AppendRichTextBox("剩余等待时间：" + i * 5);
                System.Threading.Thread.Sleep(5000);
            }

            AppendRichTextBox("连接成功……");

            //网页数据重测次数4次，等待7秒
            string httpMsg = null;

            for (int i = 0; i < 5; i++)
            {
                httpMsg = GetModemMessage();
                if (string.IsNullOrEmpty(httpMsg) || httpMsg.Length < 100 || httpMsg.Contains("1,1,1,1,") == false)
                {
                    AppendRichTextBox("未能获得光猫配置数据");
                }
                else break;//成功获取网页数据

                //显示等待时间8秒
                AppendRichTextBox("等待重新获取产品网页数据，等待时间8秒……");
                System.Threading.Thread.Sleep(8000);
            }

            if (string.IsNullOrEmpty(httpMsg)) return false;//如果不能获得网页数据，则返回失败

            Dictionary<string, string> listValue = GetDictionary(httpMsg);//从网页上获取需要检查的信息

            if (device == null)
            {
                AppendRichTextBox("获取Device_Data产品数据失败……");

                return false;
            }

            //检查出厂信息

            if (deviceType == null)
            {
                AppendRichTextBox("未能获得产品类型对应的检测信息，检测失败");
                return false;
            }

            //检查产品信息是否正确
            bool checkReult = CheckDeviceMsg(device, listValue, deviceType);

            if (checkReult == false)
            {
                AppendRichTextBox("信息检查完毕，检查失败");

                return false;
            }
            else
            {
                AppendRichTextBox("信息检查完毕，检查成功");
                return true;
            }
        }

        /// <summary>
        /// 获取网页数据
        /// </summary>
        /// <returns></returns>
        private string GetModemMessage()
        {
            //使用新的类YcdTelnetClass
            if (portOffset >= 800) portOffset = 0;
            portOffset++;

            HttpBaseClass http = new HttpBaseClass(_localIp, _localPort + portOffset, _modemIp, 8080);

            var startRet = http.Start();

            //LogHelper.WriteDebugLogTxt("成功_"+_localIp, "开启SOCKET客户端成功");

            if (startRet == false) return null;

            HttpArgs httpArgs = new HttpArgs();
            httpArgs.Url = "/cgi-bin/cgic_systeminfo.cgi";
            httpArgs.Host = "192.168.1.1:8080";
            httpArgs.Cookie = "";

            string modemMsg = http.GetHttpMsg(httpArgs, "Compile");

            //LogHelper.WriteDebugLogTxt("获取网页数据成功_" + _localIp, modemMsg);
            System.Threading.Thread.Sleep(300);

            http.Close();

            return modemMsg;
        }

        /// <summary>
        /// 检查产品相关的出厂信息得出结果
        /// </summary>
        /// <param name="device"></param>
        /// <param name="dict"></param>
        /// <returns></returns>
        private bool CheckDeviceMsg(Device_Data device, Dictionary<string, string> dict, Device_Type type)
        {
            if (device == null || dict == null || type == null) return false;

            //写入信息到测试结果中
            string value = null;

            //youhua_add_180102
            if (dict.TryGetValue("Manufacturer", out value) && value == type.Manufacturer)
            {
                AppendRichTextBox("Manufacturer检查通过");
            }
            else
            {
                AppendRichTextBox("Manufacturer检查未通过");
                return false;
            }

            //产品型号
            if (dict.TryGetValue("ProductClass", out value) && value == type.DeviceType.Replace(" ", ""))
            {
                AppendRichTextBox("ProductClass检查通过");
            }
            else
            {
                AppendRichTextBox("ProductClass检查未通过");
                return false;
            }

            //硬件版本
            if (dict.TryGetValue("HWVersion", out value) && value == type.HWVersion)
            {
                AppendRichTextBox("HWVersion检查通过");
            }
            else
            {
                AppendRichTextBox("HWVersion检查未通过");
                return false;
            }

            //软件版本
            if (dict.TryGetValue("SWVersion", out value) && value == type.SWVersionInside)
            {
                AppendRichTextBox("SWVersion检查通过");
            }
            else
            {
                AppendRichTextBox("SWVersion检查未通过");
                return false;
            }

            //MAC
            if (dict.TryGetValue("MAC", out value) && value == device.MACAddr.Trim())
            {
                AppendRichTextBox("MAC检查通过");
            }
            else
            {
                AppendRichTextBox("MAC检查未通过");
                return false;
            }

            //OUI1
            if (dict.TryGetValue("OUI", out value) && value == device.OUI1.Trim())
            {
                AppendRichTextBox("OUI检查通过");
            }
            else
            {
                AppendRichTextBox("OUI检查未通过");
                return false;
            }

            //OUI2
            if (dict.TryGetValue("SerialNum", out value) && value == device.OUI2.Trim())
            {
                AppendRichTextBox("SerialNum检查通过");
            }
            else
            {
                AppendRichTextBox("SerialNum检查未通过");
                return false;
            }
            //xponMode
            if (dict.TryGetValue("xponMode", out value) && value == type.XPONMode)
            {
                AppendRichTextBox("xponMode检查通过");
            }
            else
            {
                AppendRichTextBox("xponMode检查未通过");
                return false;
            }

            //BOSA类型，1代表GPON，2代表EPON
            string mode = "2";

            //只有xpon为GPON时才检查SN号码
            if (type.XPONMode == "GPON")
            {
                mode = "1";

                if (dict.TryGetValue("GPON_SN", out value) && value == device.XPON_SN.Trim())
                {
                    AppendRichTextBox("GPON_SN检查通过");
                }
                else
                {
                    AppendRichTextBox("GPON_SN检查未通过");
                    return false;
                }
            }

            //Mode_只有R方案检查
            if (type.DeviceType == "PT924" || type.DeviceType == "PT924G")
            {
                if (dict.TryGetValue("Mode", out value) && value == mode)
                {
                    AppendRichTextBox("Mode检查通过");
                }
                else
                {
                    AppendRichTextBox("Mode检查未通过");
                    return false;
                }
            }

            //username
            if (dict.TryGetValue("username", out value) && value == device.WedUser.Trim())
            {
                AppendRichTextBox("username检查通过");
            }
            else
            {
                AppendRichTextBox("username检查未通过");
                return false;
            }
            //password
            if (dict.TryGetValue("web_passwd", out value) && value == device.WedPassword.Trim())
            {
                AppendRichTextBox("web_passwd检查通过");
            }
            else
            {
                AppendRichTextBox("web_passwd检查未通过");
                return false;
            }
            //SSID1
            if (dict.TryGetValue("SSID1", out value) && value == device.WIFI_SSID.Trim())
            {
                AppendRichTextBox("SSID1检查通过");
            }
            else
            {
                AppendRichTextBox("SSID1检查未通过");
                return false;
            }
            //SSID PWD
            if (dict.TryGetValue("WPAPSK1", out value) && value == device.WIFI_Password.Trim())
            {
                AppendRichTextBox("WPAPSK1检查通过");
            }
            else
            {
                AppendRichTextBox("WPAPSK1检查未通过");
                return false;
            }

            //SSID 2，如果数据库中有SSID2则检查
            if (string.IsNullOrEmpty(device.ITV_SSID.Trim()) == false)
            {
                //SSID2
                if (dict.TryGetValue("SSID2", out value) && value == device.ITV_SSID.Trim())
                {
                    AppendRichTextBox("SSID2检查通过");
                }
                else
                {
                    AppendRichTextBox("SSID2检查未通过");
                    return false;
                }

                //SSID 2 PWD

                if (dict.TryGetValue("WPAPSK2", out value) && value == device.ITV_Password.Trim())
                {
                    AppendRichTextBox("WPAPSK2检查通过");
                }
                else
                {
                    AppendRichTextBox("WPAPSK2检查未通过");
                    return false;
                }
            }

            //wanTelnet
            if (dict.TryGetValue("WanTelnet", out value) && value == type.WlanTelnet)
            {
                AppendRichTextBox("Wan Telnet检查通过");
            }
            else
            {
                AppendRichTextBox("Wan Telnet检查未通过");
                return false;
            }
            //LanTelnet
            if (dict.TryGetValue("LanTelnet", out value) && value == type.LanTelnet)
            {
                AppendRichTextBox("Lan Telnet检查通过");
            }
            else
            {
                AppendRichTextBox("Lan Telnet检查未通过");
                return false;
            }

            //checksum，信息校验，R方案需要检查checkSum
            if (type.DeviceType == "PT924" || type.DeviceType == "PT924G")
            {
                if (dict.TryGetValue("securitycheck", out value) && value == type.securitycheck)
                {
                    AppendRichTextBox("security check检查通过");
                }
                else
                {
                    AppendRichTextBox("security check 检查未通过");
                    return false;
                }
            }

            //WanConnect
            if (dict.TryGetValue("WanConnect", out value) && value == type.WanConnect)
            {
                AppendRichTextBox("WanConnect检查通过");
            }
            else
            {
                AppendRichTextBox("WanConnect检查未通过");
                return false;
            }

            //PluginNum
            if (dict.TryGetValue("PluginNum", out value) && value == type.PluginNum)
            {
                AppendRichTextBox("PluginNum检查通过");
            }
            else
            {
                AppendRichTextBox("PluginNum检查未通过");
                return false;
            }

            //pluginName
            if (dict.TryGetValue("PluginName", out value) && value == type.PluginName)
            {
                AppendRichTextBox("PluginName检查通过");
            }
            else
            {
                AppendRichTextBox("PluginName检查未通过");
                return false;
            }
            //pluginRun
            if (dict.TryGetValue("PluginRun", out value) && value == type.PluginRun)
            {
                AppendRichTextBox("PluginRun检查通过");
            }
            else
            {
                AppendRichTextBox("PluginRun检查未通过");
                return false;
            }
            //Framework1
            if (dict.TryGetValue("Framework1", out value) && value == type.FrameWork1)
            {
                AppendRichTextBox("Framework1检查通过");
            }
            else
            {
                AppendRichTextBox("Framework1检查未通过");
                return false;
            }
            //Framework2
            if (dict.TryGetValue("Framework2", out value) && value == type.FrameWork2)
            {
                AppendRichTextBox("Framework2检查通过");
            }
            else
            {
                AppendRichTextBox("Framework2检查未通过");
                return false;
            }

            //APPS
            if (dict.TryGetValue("APPS", out value) && value == type.APPS)
            {
                AppendRichTextBox("APPS检查通过");
            }
            else
            {
                AppendRichTextBox("APPS检查未通过");
                return false;
            }
            //Framework(active)
            if (dict.TryGetValue("Framework(active)", out value) && value == type.FrameworkActive)
            {
                AppendRichTextBox("Framework (active)检查通过");
            }
            else
            {
                AppendRichTextBox("Framework (active)检查未通过");
                return false;
            }
            //URL
            if (dict.TryGetValue("URL", out value) && value == type.URL)
            {
                AppendRichTextBox("URL检查通过");
            }
            else
            {
                AppendRichTextBox("URL检查未通过");
                return false;
            }
            //RelativeURL
            if (dict.TryGetValue("RelativeURL", out value) && value == type.RelativeURL)
            {
                AppendRichTextBox("Relative URL检查通过");
            }
            else
            {
                AppendRichTextBox("Relative URL检查未通过");
                return false;
            }
            //LastChangedRev
            if (dict.TryGetValue("LastChangedRev", out value) && value == type.SWVersion)
            {
                AppendRichTextBox("Last Changed Rev检查通过");
            }
            else
            {
                AppendRichTextBox("Last Changed Rev检查未通过");
                return false;
            }
            //LastChangedData
            if (dict.TryGetValue("LastChangedDate", out value) && value == type.LastChangedDate)
            {
                AppendRichTextBox("Last Changed Date检查通过");
            }
            else
            {
                AppendRichTextBox("Last Changed Date检查未通过");
                return false;
            }

            return true;
        }

        /// <summary>
        /// 将光猫数据从字符串转换为键值对
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        private Dictionary<string, string> GetDictionary(string msg)
        {
            if (string.IsNullOrEmpty(msg)) return null;

            var dict = new Dictionary<string, string>();
            //去除信息中的所有空格
            msg = msg.Replace(" ", "");
            //去掉所有横杠
            //msg = msg.Replace("-", "");

            //将信息按照换行符分割，并去除掉头尾的空白字符
            var listMsg = msg.Split('\n');

            //继续将信息按照冒号分割成键值对
            for (int i = 0; i < listMsg.Length; i++)
            {
                var temp = listMsg[i].Split(':');

                //获取key和value
                string key = null;
                string value = null;

                if (temp.Length == 2)
                {
                    key = temp[0].Trim();
                    value = temp[1].Trim();
                }
                else if (temp.Length > 2)
                {
                    key = temp[0].Trim();

                    for (int j = 1; j < temp.Length; j++)
                    {
                        value += temp[j].Trim();
                    }
                }

                if (key == null) continue;

                //增加键值对
                if (dict.ContainsKey(key) == false)
                {
                    dict.Add(key, value);
                }
                else
                {
                    string keyValue = null;
                    dict.TryGetValue(key, out keyValue);

                    keyValue += "," + value;
                    dict.Remove(key);
                    dict.Add(key, keyValue);
                }
            }
            return dict;
        }

        #endregion


        /// <summary>
        /// 获取产品类型信息
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private Device_Type GetDeviceType(string type,string province)
        {
            var device = (from t in _listType
                          where t.DeviceType == type&&t.PROVINCE==province
                          select t).FirstOrDefault();

            return device;
        }



        //定位到mac输入位置，重置信息
        private void MacFocus()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                //清除list中的mac信息
                this.textBoxMacAddr.Clear();
                //this.textBoxXponSn.Clear();
                //this.textBoxMacAddr.Focus();
                //this.labelTestResult.ForeColor = Color.Black;
                //this.labelTestResult.Text = "";
            }
        }

        //设置textBox是否能够使用
        private void SetMacTextBoxEnable(bool enable = false)
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action<bool> d = new Action<bool>(SetMacTextBoxEnable);
                Invoke(d, enable);
            }
            else
            {
                this.textBoxMacAddr.Enabled = enable;
            }
        }

        //将信息检查信息窗口
        private void AppendRichTextBox(string value)
        {
            if (this.richTextBoxMsg.InvokeRequired)
            {
                Action<string> d = new Action<string>(AppendRichTextBox);
                Invoke(d, new object[] { value });
            }
            else
            {
                if (value == null) return;
                if (this.richTextBoxMsg.TextLength >= 5000)
                    this.richTextBoxMsg.Clear();
                this.richTextBoxMsg.AppendText(value);
                this.richTextBoxMsg.AppendText("\n");

                WriteLog(value);
            }
        }

        //设置结果
        private void SetTestResult(bool result, string msg = null)
        {
            if (labelTestResult.InvokeRequired)
            {
                Action<bool, string> d = new Action<bool, string>(SetTestResult);
                Invoke(d, result, msg);
            }
            else
            {
                if (result && msg == null)
                {
                    this.labelTestResult.ForeColor = Color.Green;
                    this.labelTestResult.Text = "PASS";
                }
                else if (result == false && msg == null)
                {
                    this.labelTestResult.ForeColor = Color.Red;
                    this.labelTestResult.Text = "FAIL";
                }
                else if (msg != null && result == false)
                {
                    this.labelTestResult.ForeColor = Color.Black;
                    this.labelTestResult.Text = msg;
                }
                else if (msg != null && result)
                {
                    this.labelTestResult.ForeColor = Color.BlueViolet;
                    this.labelTestResult.Text = msg;
                }
            }
        }

        //给外部使用的获取焦点方法
        public void SetFocusMac()
        {
            if (this.textBoxMacAddr.InvokeRequired)
            {
                Action d = new Action(MacFocus);
                Invoke(d);
            }
            else
            {
                this.textBoxMacAddr.Focus();
            }
        }

        private object lockLog = new object();//锁定LOG写
        /// <summary>
        /// 写log信息
        /// </summary>
        /// <param name="msg"></param>
        private void WriteLog(string msg)
        {
            lock (lockLog)
                _log = string.Format("{0}{1}\n", _log, msg);
        }

        /// <summary>
        /// 一个信息检查结束时操作
        /// </summary>
        private void FinallyDone(string macAddr, bool result = false)
        {
            PublicData.ListAddress.Remove(macAddr);
            SetTestResult(result);//展示最后结果

            //判断光猫是否已经拔出了，如果拔出了，显示等待中
            while (true)
            {
                bool linkStatus = PingBaseClass.PingTest(_localIp, _modemIp);/*ArpBaseClass.IsIpEnabled(_localIp);*/
                if (linkStatus == false)
                    break;//没有连接，直接结束

                System.Threading.Thread.Sleep(500);
            }

            SetTestResult(false, "WAIT");

            SetMacTextBoxEnable(true);//设置textbox可用
            MacFocus();//清空mac/sn
        }

        private void richTextBoxMsg_TextChanged(object sender, EventArgs e)
        {
            richTextBoxMsg.SelectionStart = richTextBoxMsg.Text.Length;
            richTextBoxMsg.ScrollToCaret();
        }

        //写单项结果
        private void SetResultOne(string msg, bool result)
        {
            if (this.labelResultOne.InvokeRequired)
            {
                Action<string, bool> d = new Action<string, bool>(SetResultOne);
                Invoke(d, msg, result);
            }
            else
            {
                this.labelResultOne.Text = msg;
                if (result) this.labelResultOne.ForeColor = Color.Green;
                else this.labelResultOne.ForeColor = Color.Red;
            }
        }

    }
}
